const http = require("http");

const conn = require("./libs/database");
const md5 = require("md5-node");

const app = http
  .createServer(async (req, res) => {
    /*
    GET   用户获取数据
    POST  用户添加数据
    PUT   用户更新数据
    DELETE  删除数据
    */
    const targetUrl = "/api/user";
    switch (req.method) {
      case "POST": {
        if (req.url === targetUrl) {
          // post 数据在原生js里采用的是分段提交方式，为了保证数据的完整性，发送完毕需要重新拼装数据
          let arr = [];
          // data事件会触发很多次
          req.on("data", data => {
            arr.push(data);
          });
          // end表示数据接收完毕，只会发生一次
          req.on("end", async () => {
            let buffer = Buffer.concat(arr);
            let { username, password } = JSON.parse(buffer.toString());
            // console.log(username, password);
            // 存入数据库
            // 1.检验数据是否存在，用户名和密码是否存在，如果存在就意味着用户已注册
            const data = await conn.query(
              `SELECT user FROM admin WHERE user = '${username}'`
            );
            if (data.length >= 1) {
              res.end(JSON.stringify({ code: 200, message: "用户名已注册" }));
            } else {
              password = md5(password);
              const sql = `INSERT INTO admin (user,password) values ('${username}','${password}')`;
              await conn.query(sql);
              res.end(JSON.stringify({ code: 200, message: "注册成功" }));
            }
          });
        }
        break;
      }
      case "GET": {
        if (req.url === targetUrl) {
          const sql = `SELECT id,user FROM admin`;
          const data = await conn.query(sql);
          res.end(JSON.stringify(data));
        }
        break;
      }
    }
  })
  .listen(3000);
